<template>
  <div class="app-container">
    <!-- 主容器 -->
    <el-row :gutter="20">
      <!-- 左侧构筑物列表 -->
      <el-col :span="6">
        <el-card>
          <el-tree 
            :data="structureTree" 
            :props="treeProps" 
            node-key="structureId" 
            highlight-current
            :expand-on-click-node="false" 
            @node-click="handleNodeClick"
            v-loading="structureLoading"
          >
            <template #default="{ node, data }">
              <div class="tree-node">
                <span>{{ node.label }}</span>
                <span v-if="data.type === 'facility'" class="facility-code">
                  {{ data.facilityNumber }}
                </span>
              </div>
            </template>
          </el-tree>
        </el-card>
      </el-col>

      <!-- 右侧设施列表 -->
      <el-col :span="18">
        <el-card>
          <el-button type="primary" @click="showAddDialog" icon="Plus">新增设施</el-button>
          
          <!-- 设施表格 -->
          <el-table 
            :data="facilityList" 
            border 
            class="mt-2" 
            v-loading="facilityLoading"
            :cell-style="{ textAlign: 'center' }"
            :header-cell-style="{ textAlign: 'center', fontWeight: 'bold' }"
          >
            <el-table-column prop="facilityName" label="设施名称" />
            <el-table-column prop="facilityNumber" label="编号" />
            <el-table-column prop="facilityType" label="类型" />
            <el-table-column prop="structureName" label="所属构筑物" />
            <el-table-column prop="remark" label="描述" />
            <el-table-column label="操作" width="180" fixed="right">
              <template #default="scope">
                <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
                <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <!-- 分页 -->
          <el-pagination 
            class="mt-2" 
            v-model:current-page="queryParams.pageNum" 
            v-model:page-size="queryParams.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 新增设施对话框 -->
    <el-dialog 
      v-model="addDialogVisible" 
      title="新增设施" 
      width="50%" 
      :close-on-click-modal="false"
    >
      <el-form 
        :model="addForm" 
        label-width="120px" 
        :rules="rules" 
        ref="addFormRef"
      >
        <el-form-item label="设施名称" prop="facilityName">
          <el-input v-model="addForm.facilityName" placeholder="请输入设施名称" />
        </el-form-item>
        <el-form-item label="编号" prop="facilityNumber">
          <el-input v-model="addForm.facilityNumber" placeholder="请输入编号" />
        </el-form-item>
        <el-form-item label="类型" prop="facilityType">
          <el-select 
            v-model="addForm.facilityType" 
            placeholder="请选择类型"
            style="width: 100%"
          >
            <el-option 
              v-for="item in facilityTypeOptions" 
              :key="item.dictValue" 
              :label="item.dictLabel" 
              :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属构筑物" prop="structureId">
          <el-select 
            v-model="addForm.structureId" 
            placeholder="请选择构筑物"
            style="width: 100%"
          >
            <el-option 
              v-for="item in structureOptions" 
              :key="item.structureId" 
              :label="item.structureName" 
              :value="item.structureId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="remark">
          <el-input v-model="addForm.remark" type="textarea" :rows="2" placeholder="请输入描述信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmAdd">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑设施对话框 -->
    <el-dialog 
      v-model="editDialogVisible" 
      title="编辑设施" 
      width="50%" 
      :close-on-click-modal="false"
    >
      <el-form 
        :model="editForm" 
        label-width="120px" 
        :rules="rules" 
        ref="editFormRef"
      >
        <el-form-item label="设施名称" prop="facilityName">
          <el-input v-model="editForm.facilityName" placeholder="请输入设施名称" />
        </el-form-item>
        <el-form-item label="编号" prop="facilityNumber">
          <el-input v-model="editForm.facilityNumber" placeholder="请输入编号" />
        </el-form-item>
        <el-form-item label="类型" prop="facilityType">
          <el-select 
            v-model="editForm.facilityType" 
            placeholder="请选择类型"
            style="width: 100%"
          >
            <el-option 
              v-for="item in facilityTypeOptions" 
              :key="item.dictValue" 
              :label="item.dictLabel" 
              :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属构筑物" prop="structureId">
          <el-select 
            v-model="editForm.structureId" 
            placeholder="请选择构筑物"
            style="width: 100%"
          >
            <el-option 
              v-for="item in structureOptions" 
              :key="item.structureId" 
              :label="item.structureName" 
              :value="item.structureId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="remark">
          <el-input v-model="editForm.remark" type="textarea" :rows="2" placeholder="请输入描述信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmEdit">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getStructureList,
  getFacilityTypeList,
  getFacilityList,
  getFacilityDetail,
  addFacility,
  updateFacility,
  deleteFacility
} from '@/api/prod_operate/sys_setting/basic/facility_setup'

// 加载状态
const structureLoading = ref(false)
const facilityLoading = ref(false)

// 构筑物选项
const structureOptions = ref([])

// 设施类型选项
const facilityTypeOptions = ref([])

// 设施列表数据
const facilityList = ref([])

// 总记录数
const total = ref(0)

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  structureId: undefined
})

// 新增表单
const addForm = reactive({
  facilityName: '',
  facilityNumber: '',
  facilityType: '',
  structureId: '',
  remark: ''
})

// 编辑表单
const editForm = reactive({
  facilityId: '',
  facilityName: '',
  facilityNumber: '',
  facilityType: '',
  structureId: '',
  remark: ''
})

// 对话框控制
const addDialogVisible = ref(false)
const editDialogVisible = ref(false)

// 表单引用
const addFormRef = ref(null)
const editFormRef = ref(null)

// 表单验证规则
const rules = reactive({
  facilityName: [
    { required: true, message: '请输入设施名称', trigger: 'blur' }
  ],
  facilityNumber: [
    { required: true, message: '请输入编号', trigger: 'blur' }
  ],
  facilityType: [
    { required: true, message: '请选择类型', trigger: 'change' }
  ],
  structureId: [
    { required: true, message: '请选择所属构筑物', trigger: 'change' }
  ]
})

// 初始化数据
const initData = async () => {
  try {
    structureLoading.value = true
    
    // 获取构筑物列表
    const structureRes = await getStructureList()
    structureOptions.value = structureRes.data.map(item => ({
      structureId: item.id,
      structureName: item.name
    }))
    
    // 获取设施类型列表
    const typeRes = await getFacilityTypeList()
    facilityTypeOptions.value = typeRes.data
    
    // 获取设施列表
    await fetchFacilityList()
  } catch (error) {
    console.error('初始化数据失败:', error)
    ElMessage.error('初始化数据失败')
  } finally {
    structureLoading.value = false
  }
}

// 获取设施列表
const fetchFacilityList = async () => {
  try {
    facilityLoading.value = true
    const res = await getFacilityList(queryParams)
    facilityList.value = res.rows.map(item => ({
      ...item,
      structureName: structureOptions.value.find(s => s.structureId === item.structureId)?.structureName || ''
    }))
    total.value = res.total
  } catch (error) {
    console.error('获取设施列表失败:', error)
    ElMessage.error('获取设施列表失败')
  } finally {
    facilityLoading.value = false
  }
}

// 生成树形结构数据
const structureTree = computed(() => {
  return structureOptions.value.map(structure => {
    return {
      structureId: structure.structureId,
      label: structure.structureName,
      type: 'structure',
    }
  })
})

// Tree配置
const treeProps = {
  children: 'children',
  label: 'label'
}

// 处理节点点击
const handleNodeClick = (data) => {
  if (data.type === 'structure') {
    queryParams.structureId = data.structureId
    fetchFacilityList()
  }
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  fetchFacilityList()
}

// 处理当前页变化
const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  fetchFacilityList()
}

// 显示新增对话框
const showAddDialog = () => {
  addForm.facilityName = ''
  addForm.facilityNumber = ''
  addForm.facilityType = ''
  addForm.structureId = queryParams.structureId || ''
  addForm.remark = ''
  addDialogVisible.value = true
}

// 确认新增
const confirmAdd = async () => {
  try {
    await addFormRef.value.validate()
    
    await addFacility(addForm)
    ElMessage.success('新增设施成功')
    addDialogVisible.value = false
    fetchFacilityList()
  } catch (error) {
    console.error('新增设施失败:', error)
    if (error.message) {
      ElMessage.error(error.message)
    }
  }
}

// 处理编辑
const handleEdit = async (row) => {
  try {
    facilityLoading.value = true
    const res = await getFacilityDetail(row.facilityId)
    Object.assign(editForm, res.data)
    editDialogVisible.value = true
  } catch (error) {
    console.error('获取设施详情失败:', error)
    ElMessage.error('获取设施详情失败')
  } finally {
    facilityLoading.value = false
  }
}

// 确认编辑
const confirmEdit = async () => {
  try {
    await editFormRef.value.validate()
    
    await updateFacility(editForm)
    ElMessage.success('修改设施成功')
    editDialogVisible.value = false
    fetchFacilityList()
  } catch (error) {
    console.error('修改设施失败:', error)
    if (error.message) {
      ElMessage.error(error.message)
    }
  }
}

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该设施吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteFacility(row.facilityId)
      ElMessage.success('删除成功')
      fetchFacilityList()
    } catch (error) {
      console.error('删除设施失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    // 取消删除
  })
}

// 初始化
onMounted(() => {
  initData()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.el-pagination {
  margin-top: 20px;
  text-align: right;
}

.el-select {
  width: 100%;
}

.el-table {
  margin-top: 20px;
}

.tree-node {
  display: flex;
  justify-content: space-between;
  width: 100%;
}

.facility-code {
  color: #909399;
  font-size: 12px;
  margin-left: 10px;
}
</style>